<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <div class="header" :class="fixedClass">
          <el-row class="header-row" :gutter="0" align="middle">
            <div class="logo-box hidden-md-and-down">
              <el-row align="middle" style="height: 100%">
                <el-image :src="require('@/assets/logo.png')" style="height: 17px;width: 81px"></el-image>
              </el-row>
            </div>
            <el-dropdown trigger="click">
              <div class="logo-box hidden-md-and-up">
                <el-row align="middle" style="height: 100%">
                  <el-image :src="require('@/assets/logo.png')" style="height: 17px;width: 81px"></el-image>
                  <ILine-mdChevron-small-down/>
                </el-row>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="$router.push('/')">首页</el-dropdown-item>
                  <el-dropdown-item>标签</el-dropdown-item>
                  <el-dropdown-item>分类</el-dropdown-item>
                  <el-dropdown-item>关于</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-menu class="el-menu-demo hidden-md-and-down" mode="horizontal" :ellipsis="false">
              <el-menu-item index="0" @click="$router.push('/')">首页</el-menu-item>
              <el-menu-item index="1">标签</el-menu-item>
              <el-menu-item index="2">分类</el-menu-item>
              <el-menu-item index="3">归档</el-menu-item>
              <el-menu-item index="4">动态</el-menu-item>
              <el-sub-menu index="5">
                <template #title>关于</template>
                <el-menu-item index="2-1">item one</el-menu-item>
                <el-menu-item index="2-2">item two</el-menu-item>
                <el-menu-item index="2-3">item three</el-menu-item>
                <el-sub-menu index="2-4">
                  <template #title>item four</template>
                  <el-menu-item index="2-4-1">item one</el-menu-item>
                  <el-menu-item index="2-4-2">item two</el-menu-item>
                  <el-menu-item index="2-4-3">item three</el-menu-item>
                </el-sub-menu>
              </el-sub-menu>
            </el-menu>
            <div class="flex-grow"/>
            <el-input v-model="searchKeyword" class="search-input" ref="searchInput" @focus="searchFocus"
                      @blur="searchBlur" :style="{width:searchInputWidth}"
                      placeholder="Ctrl + K 搜索文章">
              <template #append>
                <el-button icon="Search"/>
              </template>
            </el-input>
            <el-tooltip content="写文章" effect="light">
              <el-button v-show="showEdit" class="hidden-sm-and-down" style="width: 40px;height: 40px"
                         @click="toEdit" text>
                <el-icon :size="20">
                  <ILine-mdEdit/>
                </el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="切换主题" effect="light">
              <el-button class="hidden-sm-and-down" style="width: 40px;height: 40px" @click="switchTheme" text>
                <el-icon v-if="isDark" :size="20">
                  <ILine-mdSun-rising-loop/>
                </el-icon>
                <el-icon v-else :size="20">
                  <ILine-mdMoon/>
                </el-icon>
              </el-button>
            </el-tooltip>
            <el-dropdown>
              <div class="avatar" v-show="showAvatar">
                <el-row align="middle" style="height: 100%" justify="center">
                  <el-avatar :size="30" src="https://i03piccdn.sogoucdn.com/9157a082917ae3d1"></el-avatar>
                  <ILine-mdChevron-small-down/>
                </el-row>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>轻歌离弦</el-dropdown-item>
                  <el-dropdown-item @click="$router.push('/write')" divided>写文章</el-dropdown-item>
                  <el-dropdown-item @click="switchTheme">切换主题</el-dropdown-item>
                  <el-dropdown-item divided>个人中心</el-dropdown-item>
                  <el-dropdown-item disabled>Action 5</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-row>
        </div>
      </el-header>
      <el-container>
        <router-view></router-view>
      </el-container>
      <el-backtop :right="backtopRight" :bottom="40"/>
    </el-container>
  </div>
</template>

<script>
import {useDark, useToggle} from '@vueuse/core'
import {COLOR_SCHEME_CACHE_KEY} from "@/js/constants";
import {customSetItem} from "@/js/utils";

const toDark = useDark()

export default {
  name: "Home",
  data() {
    return {
      isDark: false, // 刷新时不会初始化
      searchKeyword: "",
      searchInputFocused: false,
      avatarXs: 5,
      searchInputXs: 13,
      searchInputSm: 11,
      searchInputMd: 6,
      searchInputLg: 6,
      searchInputXl: 6,
      writeBtnSm: 2,
      writeBtnMd: 2,
      writeBtnLg: 2,
      writeBtnXl: 1,
      showEdit: true,
      showAvatar: true,
      fixedClass: "fixed",
    }
  },
  methods: {
    toRender() {
      console.log(this.$route.params) // $route当前路由
      this.$router.push("/render") // $router就是我们createRouter创建的路由
    },
    toggleDark() {
      const toDarkResult = useToggle(toDark)()
      customSetItem(COLOR_SCHEME_CACHE_KEY, toDarkResult ? "dark" : "light")
      return toDarkResult
    },
    keyMonitor() {
      let pressCtrl = false
      let pressK = false
      document.onkeydown = (e) => {
        let _event = e || event
        let keyCode = _event.keyCode || _event.which || _event.charCode
        if (keyCode === 17) {
          pressCtrl = true
        }
        if (keyCode === 75) {
          pressK = true
        }
        if (pressCtrl && pressK) {
          e.preventDefault()
          this.searchInputFocused = !this.searchInputFocused
        }
      }
      document.onkeyup = (e) => {
        let _event = e || event
        let keyCode = _event.keyCode || _event.which || _event.charCode
        if (keyCode === 17) {
          pressCtrl = false
        }
        if (keyCode === 75) {
          pressK = false
        }
      }
    },
    searchFocus() {
      if (this.screenWidth >= 768) {
        this.showEdit = false
      } else {
        this.showAvatar = false
      }
    },
    searchBlur() {
      if (this.screenWidth >= 768) {
        this.showEdit = true
      } else {
        this.showAvatar = true
      }
    },
    switchTheme() {
      this.toggleDark()
      this.$unFocus()
    },
    toEdit() {
      this.$router.push('/write')
      this.$unFocus()
    },
    // 防抖
    debounce(func, wait) {
      let timeout;
      return function () {
        let context = this
        let args = arguments
        if (timeout) clearTimeout(timeout)
        timeout = setTimeout(() => {
          func.apply(context, args)
        }, wait)
      }
    },
  },
  created() {
    this.isDark = localStorage.getItem(COLOR_SCHEME_CACHE_KEY) === "dark"
  },
  mounted() {
    // 监听storage
    window.addEventListener("setItem", (e) => {
      if (e.key === COLOR_SCHEME_CACHE_KEY) {
        this.isDark = e.newValue === "dark"
      }
    })
    // 跨标签页监听storage
    window.onstorage = (e) => {
      if (e.key === COLOR_SCHEME_CACHE_KEY) {
        this.isDark = e.newValue === "dark"
      }
    }

    this.keyMonitor()

    // window.onscroll
    const _this = this
    const handleScroll = function () {
      let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
      if (this.lastScrollTop !== undefined) {
        if (scrollTop > this.lastScrollTop) {
          if (scrollTop > 200 && _this.fixedClass === "fixed") {
            _this.fixedClass = ""
          }
        } else {
          if (_this.fixedClass !== "fixed") {
            _this.fixedClass = "fixed"
          }
        }
      }
      this.lastScrollTop = scrollTop
    }
    window.addEventListener("scroll", this.debounce(handleScroll, 200))

  },
  computed: {
    searchInputWidth() {
      let hiddenWidth = 0
      if (!this.showEdit) {
        hiddenWidth += 40
      }
      if (!this.showAvatar) {
        hiddenWidth += 56.8
      }
      if (this.screenWidth > 1200) {
        return (350 + hiddenWidth) + 'px'
      } else if (this.screenWidth > 480) {
        return (250 + hiddenWidth) + 'px'
      } else if (this.screenWidth > 380) {
        return (200 + hiddenWidth) + 'px'
      } else if (this.screenWidth > 330) {
        return (150 + hiddenWidth) + 'px'
      } else {
        return "0px" // 无效的，必须通过@media设置display=none
      }
    },
    backtopRight() {
      if (this.screenWidth > 800) {
        return 40
      } else {
        return 10
      }
    },
    screenWidth: {
      get() {
        return this.$store.screenWidth.value
      },
    },
  },
  watch: {
    searchInputFocused: {
      handler(newVal) {
        if (newVal) {
          this.$refs.searchInput.focus()
        } else {
          this.$refs.searchInput.blur()
        }
      },
      immediate: false,
    }
  }
}
</script>

<style lang="scss" scoped>

.el-header {
  --el-header-padding: 0 0;
}

.header {
  width: 100%;
  height: var(--el-header-height);
  border-bottom: 1px solid var(--el-border-color);
  //box-shadow: var(--el-box-shadow-lighter);
  //padding: 0 5px;
  background-color: #ffffff;
}

html.dark {

  .header {
    //box-shadow: var(--el-box-shadow-dark);
    background-color: #000000;
  }

  .avatar:hover {
    background-color: #303133;
  }

  .nav-dropdown:hover {
    background-color: #303133;
  }

  .logo-box:hover {
    background-color: #303133;
  }

}

.el-main {
  height: 1800px;
}

.el-col {
  border-radius: 4px;
  /*background-color: #8c959f;*/
}

.el-button {
  padding: 1px 6px;
}

.el-menu--horizontal {
  border: none; //去掉下边框
  height: var(--el-header-height); //撑开col和row,占满header
  padding: 0 10px;
}

.flex-grow {
  flex-grow: 1; // 父元素是flex布局时,在子元素上设置,分享父元素剩余的空间
}

.fixed {
  position: fixed;
  top: 0;
  z-index: 2; //Vditor的z-index是1，其他元素默认0
}

.avatar {
  cursor: pointer;
  height: 40px;
  padding: 0 5px;
  border-radius: var(--el-border-radius-base);
}

.avatar:hover {
  background-color: #f4f4f5;
}

.header-row {
  height: 100%;
  padding: 0 5px;
}

@media screen and (min-width: 1200px) {
  .header-row {
    padding: 0 40px;
  }
}

@media screen and (min-width: 500px) {
  .header-row {
    margin-right: calc(17px - (100vw - 100%));
  }
}

.search-input {
  :deep(.el-input-group__append) {
    background-color: var(--el-fill-color-blank);
  }

  padding: 0 5px;
  //width: 300px;
  height: 40px;
}

@media screen and (min-width: 380px) and (max-width: 480px) {
  .search-input {
    //width: 200px;
  }
}

@media screen and (min-width: 330px) and (max-width: 380px) {
  .search-input {
    //width: 150px;
  }
}

@media screen and (max-width: 330px) {
  .search-input {
    display: none;
  }
}

.nav-dropdown {
  cursor: pointer;
  padding: 15px 5px;
}

.nav-dropdown:hover {
  background-color: #f4f4f5;
}

.el-button + .el-button {
  margin-left: 0;
}

.el-button {
  padding: 0 5px;
}

.logo-box {
  height: 40px;
  padding: 0 5px;
  cursor: pointer;
  border-radius: var(--el-border-radius-base);
}

.logo-box:hover {
  background-color: #f4f4f5;
}

@media screen and (max-width: 990px) {
  .hidden-md-and-down {
    display: none;
  }
}

@media screen and (min-width: 990px) {
  .hidden-md-and-up {
    display: none;
  }
}

@media screen and (max-width: 768px) {
  .hidden-sm-and-down {
    display: none;
  }
}

</style>